import 'dart:ui';
import 'package:flutter/material.dart';

class XHFpsMonitor {
  static const int _fpsHz = 60;
  final _frameInterval =
  const Duration(microseconds: Duration.microsecondsPerSecond ~/ _fpsHz);

  static late List<int> frameMapGlobal;

  late final Function refreshFps;

  XHFpsMonitor(Function f) {
    frameMapGlobal = List<int>.filled(600, 0, growable: false);
    refreshFps = f;
  }

  void start() {
    WidgetsBinding.instance.addTimingsCallback(onTimings);
  }

  void stop() {
    WidgetsBinding.instance.removeTimingsCallback(onTimings);
  }

  void onTimings(List<FrameTiming> timings) {
    for (FrameTiming timing in timings) {
      final int skippedFrameCount =
          timing.totalSpan.inMilliseconds ~/ _frameInterval.inMilliseconds;
      if (skippedFrameCount < frameMapGlobal.length) {
        frameMapGlobal[skippedFrameCount]++;
      }
    }
    refreshFps(uiFps.toStringAsFixed(0));
  }

  num get uiFps {
    // 跳帧数量
    int skippedCount = 0;
    // 实际绘制帧数
    int drawnCount = 0;

    for (int i = 0; i < frameMapGlobal.length; i++) {
      drawnCount += frameMapGlobal[i];
      skippedCount += i * frameMapGlobal[i];
    }
    final int totalCount = drawnCount + skippedCount;
    if (totalCount > 0) {
      return _fpsHz * drawnCount / totalCount;
    }
    return _fpsHz;
  }
}